﻿Shader "Lary/RimLight FB" {
	Properties {
		_DiffuseBrightness ("Diffuse Brightness", Range (0, 1)) = 0.5
		_DiffuseSharpness ("Diffuse Sharpness", Range (1, 10)) = 1
		// The Texture for the model
		_MainTex ("Base (RGB)", 2D) = "grey" {}
		// The Rim Color, Power and Range from fully dependent of the light direction to not dependent.
		_RimColor ("Rim Color", Color) = (0.8,0.8,0.8,0.6)
        _RimPower ("Rim Power", Float) = 1.4
        _RimLightEnhance ("Rim Enhance", Range (0, 2)) = 0
        _RimLightRange ("Rim", Range (0, 2)) = 0
		// Range from light depending fully on the alpha map to not depending.
        _AlphaMapInfluence ("Alpha Map Influence", Range (0, 1)) = 0
	}
	
	SubShader {
		Tags {"RenderType"="Geometry" "LightMode" = "ForwardBase"}
		Pass
		{
			CGPROGRAM
			
			#pragma vertex vert
			#pragma fragment frag
			
			// user defined variables
			uniform sampler2D _MainTex;
			uniform half4 _MainTex_ST;
			
			//uniform fixed4 _Color;					// COLOR
			uniform half _DiffuseBrightness;		// (0-1)
			uniform half _DiffuseSharpness;			// (1-10)

			uniform fixed4 _RimColor;				// COLOR
			uniform half _RimPower;					// FLOAT
			uniform half _RimLightRange;			// (0-2)
			uniform half _RimLightEnhance;			// (0-2)
			
			uniform half _AlphaMapInfluence;        // (0-1)
			
			// unity defined variables
			uniform half4 _LightColor0;
			
			// base input structs
			struct vertexInput
			{
				float4 vertex : POSITION;
				half3 normal : NORMAL;
				half2 texcoord : TEXCOORD0;
			};
			struct vertexOutput
			{
				float4 pos : SV_POSITION;
				half2 tex : TEXCOORD;
				half4 light : COLOR;
				half2 rimValues : TEXCOORD3;
			};

			// vertex function
			vertexOutput vert (vertexInput v)
			{
				vertexOutput o;
			
				half3 normalDir = normalize( mul( half4( v.normal, 0.0 ), _World2Object ).xyz );
				half3 viewDir = normalize( _WorldSpaceCameraPos.xyz - mul(_Object2World, v.vertex).xyz );
				half3 lightDir = normalize( _WorldSpaceLightPos0.xyz );
				half dotProd = saturate (dot(normalDir, lightDir));
				
				o.pos = mul(UNITY_MATRIX_MVP, v.vertex);//+half4(v.normal.x,v.normal.y,v.normal.z,0)*0.01);
				o.tex = v.texcoord;
				
				o.light = _LightColor0 * pow(dotProd,_DiffuseSharpness) * _DiffuseBrightness;
				
				o.rimValues = half2( min(dotProd+_RimLightEnhance, 1.0) * _RimLightRange, 1 - dot( viewDir, normalDir ));

				return o;
			}
			
			// fragment function
			fixed4 frag(vertexOutput i) : COLOR
			{
				fixed4 tex = tex2D(_MainTex, i.tex * _MainTex_ST.xy + _MainTex_ST.zw);
				half3 final = tex.xyz
						+ saturate ( _RimColor.xyz * i.rimValues.x * pow (i.rimValues.y, _RimPower) ) // Rim Light
						+ i.light * lerp(1,tex.w,_AlphaMapInfluence); // Diffuse Light
				
				
				return fixed4 (saturate (final),1);
			}
			ENDCG
		}
	} 
	FallBack "Diffuse"
}
